package xyz.penghaonan.p2plib.job.jobs;

import com.penghaonan.appframework.utils.WeakObservableList;

import xyz.penghaonan.p2plib.P2PManager;
import xyz.penghaonan.p2plib.job.base.BaseJob;
import xyz.penghaonan.p2plib.job.base.JobListener;
import xyz.penghaonan.p2plib.job.base.Operation;
import xyz.penghaonan.p2plib.job.base.OperationListenerAdapter;
import xyz.penghaonan.p2plib.job.operations.CreateGroupOperation;
import xyz.penghaonan.p2plib.job.operations.DeleteGroupOperation;
import xyz.penghaonan.p2plib.job.operations.StartServiceOperation;

public class StartServerJob extends BaseJob {

    public StartServerJob() {
        DeleteGroupOperation operation = new DeleteGroupOperation();
        operation.addListener(new OperationListenerAdapter() {

            @Override
            public void onOperationFinish(Operation operation, Operation.Result result) {
                doStartServiceOperation();
            }
        });
        setHeaderOperation(operation);
    }

    private void doStartServiceOperation() {
        StartServiceOperation startServiceOperation = new StartServiceOperation();
        startServiceOperation.addListener(new OperationListenerAdapter() {

            @Override
            public void onOperationFinish(Operation operation, final Operation.Result result) {
                if (result.success) {
                    doCreateGroupOperation();
                } else {
                    jobListenerList.iterate(new WeakObservableList.OnIterator<JobListener>() {
                        @Override
                        protected boolean onIterator(JobListener item) {
                            item.onJobFinish(false, result.msg);
                            return false;
                        }
                    });
                }
            }
        });
        executeOperation(startServiceOperation);
    }

    private void doCreateGroupOperation() {
        CreateGroupOperation operation = new CreateGroupOperation();
        operation.addListener(new OperationListenerAdapter() {

            @Override
            public void onOperationFinish(Operation operation, Operation.Result result) {
                if (result.success) {
                    P2PManager.getServerSocketHelper();
                }
                notifyJobFinish(result.success, result.msg);
            }
        });
        executeOperation(operation);
    }
}
